package edu.filefind.thread;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class FileFinder extends Thread{
	
	String dirName;
	String suffix;
	static List<File> list = new ArrayList<File>();
	private boolean terminated = false;
	 
	public FileFinder(String dirName,String suffix){
		
		this.dirName = dirName;
		this.suffix = suffix;
		
	}
	

	public void run(){
		
//		try{
//			Thread.sleep(100);
//		}catch(Exception e){
//			e.printStackTrace();
//		}
//		
		
		long stTime = System.currentTimeMillis();
		List lister = findFile(dirName,suffix);
		list.addAll(lister);
		long enTime = System.currentTimeMillis();
		long costTime = enTime - stTime;
		System.out.println("Search "+dirName+" cost "+ costTime/1000.0+" s");
		
		System.out.println("===============================================");
		System.out.println("Find "+lister.size()+" Files in " + dirName);
		printFiles(lister);
		System.out.println("===============================================");
		
		this.terminated = true;

	}
	
	
	public List<File> findFile(String dirName,String suffix){
		
		List<File> lis = new ArrayList<File>();
		File file = new File(dirName);
		File[] files = file.listFiles();
		
		if(null == files){
			return lis;
		}
		
		for(int i=0;i<files.length;i++){
			
			File temp = files[i];
			
			if(temp.isFile() && temp.getName().endsWith(suffix)){
				lis.add(temp);
			}
			
			String dir = temp.getAbsolutePath();
			lis.addAll(findFile(dir,suffix));
		}
		return lis;
		
	}
	
	/**
	 * print all the elements in the the list
	 */
	public static void printAllFoundFiles(){
		
		Iterator<File> iter = list.iterator();
//		if(!iter.hasNext()){
//			System.out.println("can't find any files!");
//		}
		while(iter.hasNext()){
			System.out.println(iter.next());
		}
		
	}
	
	public void printFiles(List<File> list){
		
		Iterator<File> iter = list.iterator();
		while(iter.hasNext()){
			
			if(!iter.hasNext()){
				System.out.println("can't find any files!");
			}
			
			System.out.println(iter.next());
		}
	}
	
	public boolean isTerminated(){
		return this.terminated;
	}

}
